# -*- coding: utf-8 -*-
from PySide2.QtWidgets import QMessageBox
from PySide2.QtCore import QObject, Signal, QTimer, Qt
from gglobal import logger


class CarReconnectManager(QObject):
    """车辆重连管理器类"""
    
    # 信号定义
    reconnection_completed = Signal(bool, str)  # 重连完成信号 (是否成功, 消息)
    
    def __init__(self, language_manager, parent=None):
        """
        初始化重连管理器
        :param language_manager: 语言管理器
        :param parent: 父对象
        """
        super().__init__(parent)
        self.language_manager = language_manager
        self.parent_widget = parent
        # 重连流程内部状态
        self._awaiting_result = False  # 是否正在等待重连结果
        self._timeout_timer = None     # 超时定时器
        
    def show_reconnection_dialog(self, error_message):
        """显示重连弹窗"""
        try:
            # 创建消息框
            msg_box = QMessageBox(self.parent_widget)
            msg_box.setWindowTitle(self.language_manager.get_text("connection_error_title", "连接异常"))
            msg_box.setIcon(QMessageBox.Warning)
            
            # 设置消息内容
            dialog_message = f"{self.language_manager.get_text('connection_error_message', '车辆连接出现异常')}:\n\n{error_message}\n\n{self.language_manager.get_text('reconnection_options', '请选择操作')}"
            msg_box.setText(dialog_message)
            
            # 添加按钮
            terminate_button = msg_box.addButton(self.language_manager.get_text("terminate_connection", "终止连接"), QMessageBox.RejectRole)
            reconnect_button = msg_box.addButton(self.language_manager.get_text("reconnect", "重新连接"), QMessageBox.AcceptRole)
            
            # 设置默认按钮
            msg_box.setDefaultButton(reconnect_button)
            
            # 显示对话框并获取用户选择
            msg_box.exec_()
            clicked_button = msg_box.clickedButton()
            
            if clicked_button == terminate_button:
                # 用户选择终止连接
                self.handle_terminate_connection()
                logger.info("用户选择终止连接")
            elif clicked_button == reconnect_button:
                # 用户选择重新连接
                self.handle_reconnection()
                logger.info("用户选择重新连接")
                
        except Exception as e:
            logger.error(f"显示重连弹窗时发生错误: {str(e)}")
            # 如果弹窗显示失败，回退到简单的警告对话框
            QMessageBox.warning(self.parent_widget, "连接异常", f"连接异常: {error_message}")
    
    def handle_terminate_connection(self):
        """处理终止连接操作"""
        try:
            logger.info("开始执行终止连接操作")
            
            # 1. 停止file_manager中的命令工作线程
            if hasattr(self, 'file_manager') and self.file_manager:
                self.file_manager._stop_current_worker()
                logger.info("已停止文件管理器中的命令工作线程")
            
            # 2. 断开车辆连接并结束连接线程
            if hasattr(self, 'vehicle_connection_manager') and self.vehicle_connection_manager:
                self.vehicle_connection_manager.disconnect_from_vehicle()
                logger.info("已断开车辆连接并结束连接线程")
            
            # 3. 断开连接开关（通过vehicle_connection_manager处理）
            # 连接状态变化会自动更新UI状态
            
            logger.info("终止连接操作完成")
            
            # 发送完成信号
            self.reconnection_completed.emit(False, "连接已终止")
            
        except Exception as e:
            logger.error(f"终止连接操作时发生错误: {str(e)}")
            QMessageBox.critical(self.parent_widget, "错误", f"终止连接时发生错误: {str(e)}")
    
    def handle_reconnection(self):
        """处理重新连接操作"""
        try:
            logger.info("开始执行重新连接操作")
            
            # 直接通过vehicle_connection_manager重新连接
            if hasattr(self, 'vehicle_connection_manager') and self.vehicle_connection_manager:
                # 获取之前连接的IP地址
                last_connected_ip = getattr(self.vehicle_connection_manager, '_last_connected_ip', None)
                
                if last_connected_ip:
                    logger.info(f"尝试重新连接到IP: {last_connected_ip}")
                    
                    # 先断开当前连接（如果有的话）
                    self.vehicle_connection_manager.disconnect_from_vehicle()
                    
                    # 重新连接（异步）：仅表示开始尝试，不代表成功
                    started = self.vehicle_connection_manager.connect_to_vehicle(last_connected_ip)

                    # 若未能启动连接尝试，立即判定为失败
                    if not started:
                        result_message = f"无法开始重连到 {last_connected_ip}"
                        logger.error(f"重连启动失败: {result_message}")
                        QMessageBox.critical(
                            self.parent_widget,
                            self.language_manager.get_text("reconnection_failed_title", "重连失败"),
                            f"{self.language_manager.get_text('reconnection_failed_message', '重新连接失败')}: {result_message}"
                        )
                        self.handle_terminate_connection()
                        self.reconnection_completed.emit(False, result_message)
                        return

                    # 设置等待结果的标志，并监听一次性结果信号
                    self._awaiting_result = True

                    def on_reconnect_result(is_connected, message):
                        """一次性重连结果处理"""
                        if not self._awaiting_result:
                            return
                        # 停止并清理超时定时器
                        if self._timeout_timer:
                            try:
                                self._timeout_timer.stop()
                            except Exception:
                                pass
                            self._timeout_timer = None

                        # 断开一次性信号连接
                        try:
                            self.vehicle_connection_manager.connection_status_changed.disconnect(on_reconnect_result)
                        except Exception:
                            pass

                        self._awaiting_result = False

                        if is_connected:
                            # 重连成功（以实际连接成功事件为准）
                            result_message = f"成功重新连接到 {last_connected_ip}"
                            logger.info(f"重连成功: {result_message}")
                            QMessageBox.information(
                                self.parent_widget,
                                self.language_manager.get_text("reconnection_success_title", "重连成功"),
                                f"{self.language_manager.get_text('reconnection_success_message', '重新连接成功')}: {result_message}"
                            )
                            self.reconnection_completed.emit(True, result_message)
                        else:
                            # 重连失败
                            result_message = f"无法重新连接到 {last_connected_ip}：{message}"
                            logger.error(f"重连失败: {result_message}")
                            QMessageBox.critical(
                                self.parent_widget,
                                self.language_manager.get_text("reconnection_failed_title", "重连失败"),
                                f"{self.language_manager.get_text('reconnection_failed_message', '重新连接失败')}: {result_message}"
                            )
                            # 失败后执行终止连接操作
                            self.handle_terminate_connection()
                            self.reconnection_completed.emit(False, result_message)

                    # 连接一次性结果监听（尽量避免重复连接）
                    try:
                        self.vehicle_connection_manager.connection_status_changed.connect(on_reconnect_result, Qt.UniqueConnection)
                    except TypeError:
                        # 若UniqueConnection不支持，退回普通连接后在回调中主动断开
                        self.vehicle_connection_manager.connection_status_changed.connect(on_reconnect_result)

                    # 启动超时定时器（例如6秒），超时视为失败
                    try:
                        self._timeout_timer = QTimer(self)
                        self._timeout_timer.setSingleShot(True)
                        self._timeout_timer.setInterval(6000)

                        def on_timeout():
                            if not self._awaiting_result:
                                return
                            self._awaiting_result = False
                            # 断开结果监听
                            try:
                                self.vehicle_connection_manager.connection_status_changed.disconnect(on_reconnect_result)
                            except Exception:
                                pass
                            timeout_message = f"重连超时: {last_connected_ip}"
                            logger.error(timeout_message)
                            QMessageBox.critical(
                                self.parent_widget,
                                self.language_manager.get_text("reconnection_failed_title", "重连失败"),
                                f"{self.language_manager.get_text('reconnection_failed_message', '重新连接失败')}: {timeout_message}"
                            )
                            self.handle_terminate_connection()
                            self.reconnection_completed.emit(False, timeout_message)

                        self._timeout_timer.timeout.connect(on_timeout)
                        self._timeout_timer.start()
                    except Exception as e:
                        logger.warning(f"设置重连超时定时器失败: {e}")
                else:
                    # 没有记录的IP地址
                    error_msg = "没有找到之前连接的IP地址，无法执行重连操作"
                    logger.error(error_msg)
                    QMessageBox.critical(self.parent_widget, "重连失败", error_msg)
                    # 执行终止连接操作
                    self.handle_terminate_connection()
                    # 发送完成信号
                    self.reconnection_completed.emit(False, error_msg)
            else:
                # 无法获取vehicle_connection_manager
                error_msg = "无法获取车辆连接管理器，无法执行重连操作"
                logger.error(error_msg)
                QMessageBox.critical(self.parent_widget, "重连失败", error_msg)
                # 执行终止连接操作
                self.handle_terminate_connection()
                # 发送完成信号
                self.reconnection_completed.emit(False, error_msg)
                
        except Exception as e:
            logger.error(f"重新连接操作时发生错误: {str(e)}")
            QMessageBox.critical(self.parent_widget, "错误", f"重新连接时发生错误: {str(e)}")
            # 发生异常时执行终止连接操作
            self.handle_terminate_connection()
            # 发送完成信号
            self.reconnection_completed.emit(False, f"重连异常: {str(e)}")
    
    def process_reconnection_request(self, error_message, file_manager, vehicle_connection_manager):
        """处理重连请求的完整流程"""
        try:
            # 保存管理器引用
            self.file_manager = file_manager
            self.vehicle_connection_manager = vehicle_connection_manager
            
            # 显示重连对话框
            self.show_reconnection_dialog(error_message)
            
        except Exception as e:
            logger.error(f"处理重连请求时发生错误: {str(e)}")
            # 如果处理失败，回退到简单的警告对话框
            QMessageBox.warning(self.parent_widget, "连接异常", f"连接异常: {error_message}")